package com.kalua.list.domainmodel;

import java.net.URLDecoder;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

public final class DomainModelUtil {
	private DomainModelUtil(){}
	
	private static String DEFAULT_ENCODING = "UTF-8";
	
	public static <V extends Identifiable<K>, K extends Identifier> 
										Map<K,V> map(List<V> values) {
		Map<K, V> result = Maps.newHashMap();
		for (V value : values) {
			result.put(value.getId(), value);
		}
		return result;
	} 
	
	public static String decodeHttpString(String encodedString) {
		String result;
		try {
			if (!StringUtils.isEmpty(encodedString)) { 
				result = URLDecoder.decode(encodedString, DEFAULT_ENCODING);
				result = result.replaceAll("&amp;", "and");
			} else result = encodedString;
		} catch (IllegalArgumentException exce) {
			//not an encoded string then
			result = encodedString;
		} catch (Exception exce)  { throw new KaluaException(exce); }		
		return result;
	}

	public static HashSet<String> decodeHttpStrings(Set<String> encodedStrings) {
		HashSet<String> result = Sets.newHashSet();
		for (String encodedString : encodedStrings) 
			result.add(decodeHttpString(encodedString));			
		return result;
	}
}